import axios from 'axios';
import type { AxiosRequestConfig } from 'axios';
import { localGetToken } from '@/utils/localStorage/account';
import { getToken } from '@/utils/auth';
import { Message } from '@arco-design/web-vue';

// import useGlobalParametersStore from '@/stores/globalParameters';
// const globalParameters = useGlobalParametersStore();

const env = import.meta.env;
const service = axios.create({
  timeout: 100000, // 请求超时时间
  baseURL: env.VITE_APP_BASE_URL
});

type YXRequestConfig = AxiosRequestConfig & {
  headers?: any;
  noToken?: boolean; // 是否不需要token，默认false
  isLoading?: boolean; // 是否请求时开启全局Loading，默认false
  loadingTip?: string; // 全局Loading的提示
};

// axios请求前拦截
service.interceptors.request.use(
  async (config: YXRequestConfig) => {
    config.headers['Content-Type'] =
      config.headers['Content-Type'] || 'application/json;charset=UTF-8';

    if (!config.noToken) {
      // 判断是否需要token
      config.headers.Authorization = `${getToken()}`;
    }
    return config;
  },
  (err) => {
    console.log(err);
  }
);
type MsgType = 'success';

// axios请求后拦截
service.interceptors.response.use(
  function (response) {
    // globalParameters.setLoadingConfig(false); // 请求完成，关闭全局Loading
    // const { msgType, msg }: { msgType?: MsgType; msg: string } = response.data; // 检查msgType发送Message
    // if (msgType) Message[msgType](msg);

    const {
      msg,
      code,
      msgType
    }: { msg: string; code: number; msgType: string } =
      response.data || response;
    if (code === 200 && msgType !== 'get') Message.success(`${msg}`);
    else if (code >= 400) Message.error(`${msg}`);
    return response;
  },
  function (error) {
    // globalParameters.setLoadingConfig(false); // 请求完成，关闭全局Loading
    const status = error.response.status;
    const code = error.response.data.code;
    const msg = error.response.data.msg;
    console.log(error.response.data);

    // const { msg, code }: { msg: string; code: number } = error;
    if (code === 1001) {
      Message.error(`${msg}`);
    } else if (status === 500) {
      Message.error(`${status} :请求失败,请检查网络设置`);
    } else {
      Message.error(`${status} :请求失败,联系陈俊升查看`);
    }
    return Promise.reject(error);
  }
);

// axios封装
export async function ajaxUploadService<T>(config: YXRequestConfig) {
  if (config.isLoading) {
    // 判断是否打开全局Loading
    // globalParameters.setLoadingConfig(config.isLoading, config.loadingTip);
  }
  try {
    const res = await service(config);
    console.log('===================232323=================');
    console.log(res);
    console.log('====================================');
    return Promise.resolve(res.data);
  } catch (err: any) {
    return Promise.reject(err);
  }
}
